package com.shali.cloud.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.shali.cloud.entity.User;
import com.shali.cloud.repository.UserRepository;

@RestController
public class UserController {

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private EurekaClient eureClient;
	
	@Autowired
	private DiscoveryClient discoveryClient;
	
	//@RequestMapping(value="/findOne/{id}",method = RequestMethod.GET)
	@GetMapping("/findOne/{id}")
	public User findById(@PathVariable Long id) {
		return userRepository.findOne(id);
	}
	
	@GetMapping("/eureka-instance")
	public String serviceUrl() {
		InstanceInfo instance = eureClient.getNextServerFromEureka("MICROSERVICE-PROVIDER-USER", true);
		return instance.getHomePageUrl();
	}
	
	@GetMapping("/instance-info")
	public ServiceInstance instanceInfo() {
		@SuppressWarnings("deprecation")
		ServiceInstance serviceInstance = discoveryClient.getLocalServiceInstance();
		return serviceInstance;
	}
	
	@PostMapping("/user")
	public User user(@RequestBody User user) {
		return user;
	}
	//请求不成功，只要参数是复杂对象，即使指定了是Get请求，feign依然以Post请求方式发送
	@GetMapping("/user")
	public User getUser(@RequestBody User user) {
		return user;
	}
	
	@GetMapping("/list-all")
	public List<User> listAll(){
		ArrayList<User> userList = Lists.newArrayList();
		User u1 = new User(1L,"u1");
		User u2 = new User(2L,"u2");
		User u3 = new User(3L,"u3");
		userList.add(u1);
		userList.add(u2);
		userList.add(u3);
		return userList;
	}
}
